<!--审计日志-->
<template>
    <div>
        <a-row>
            <a-card>
                <p slot="title">
                    检索条件
                </p>
                <div class="formSearch">
                    <a-form ref="searchForm" :model="searchForm" :label-width="80" layout="inline"
                            @keydown.native.enter.prevent="handleSubmit('searchForm')">
                        <a-row>
                            <a-form-item label="用户名：" prop="userName" style="margin-right: 25px;">
                                <a-input v-model="searchForm.userName" @keyup="formatEnterContent('searchForm', 'userName','1')"
                                         @blur="formatEnterContent('searchForm', 'userName','1')"  style="width: 180px;text-align: left" placeholder="请输入用户名" >
                                    <a-icon slot="prefix" type="user"  class="displayPre"/>
                                    <a-icon v-if="searchForm.userName" slot="suffix" type="close-circle" @click="emitEmpty('searchForm', 'userName')" />
                                </a-input>
                            </a-form-item>
                            <a-form-item label="系统功能：" pro="itemCode" style="margin-right: 25px;">
                                <a-tree-select v-model="searchForm.itemCode"
                                               style="width: 200px"
                                               :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                                               :treeData="getItemsOpts" allowClear placeholder="全部">
                                    <span style="color: #08c" slot="title" slot-scope="{key, title}">{{title}}</span>
                                </a-tree-select>
                            </a-form-item>
                            <a-form-item label="操作终端：" prop="loginIp" style="margin-right: 25px;">
                                <a-input v-model="searchForm.loginIp" @keyup="formalIP('searchForm', 'loginIp','2')"
                                         @blur="formalIP('searchForm', 'loginIp','2')"   @change="validateSearchIP(searchForm.loginIp)" style="width: 180px;text-align: left"
                                         placeholder="请输入IP地址" >
                                    <a-icon slot="prefix" type="user"  class="displayPre"/>
                                    <a-icon v-if="searchForm.loginIp" slot="suffix" type="close-circle" @click="emitEmpty('searchForm', 'loginIp')" />
                                </a-input>
                                <div class="errorMsg">{{ searchErrorMsg }}</div>
                            </a-form-item>
                            <a-form-item label="日志时间：" style="margin-right: 25px;">
                                <a-date-picker
                                        :disabledDate="disabledStartDate"
                                        showTime
                                        format="YYYY-MM-DD HH:mm:ss"
                                        v-model="startValue"
                                        placeholder="开始日期"
                                        style="width: 200px; float: left"
                                />
                                <span style="width: 20px; float: left; text-align: center">-</span>
                                <a-date-picker
                                        :disabledDate="disabledEndDate"
                                        showTime
                                        format="YYYY-MM-DD HH:mm:ss"
                                        placeholder="结束日期"
                                        v-model="endValue"
                                        style="width: 200px; float: left"
                                />
                            </a-form-item>
                            <a-button type="primary" @click="handleSubmit('searchForm')"
                                      v-if="hasPermission('audit:findAuditLogs')">查询
                            </a-button>
                            <a-button style="margin-left: 8px" @click="reStore">重置</a-button>
                        </a-row>
                    </a-form>
                </div>
            </a-card>
            <div style="height: 15px"></div>
            <div class="commonStyle nyContent">
                <div class="margin-top-10 edittable-table-height-con">
                    <div style="margin: -10px auto 1px; width: 100%;text-align: right; height: 40px; line-height: 40px;">
                        <a-button @click="exportAuditLogs" style="float: left;">导出日志</a-button>
                        <!--
                        <span style="color:#ff9900">*橙色文字表示：审计日志特殊功能提醒！</span>
                        -->
                        <span style="color:#ff0000">*红色文字表示：审计日志数据被篡改！</span>
                    </div>
                    <a-table :columns="columns" :dataSource="getLogsPageData" :rowKey="record => record.id"
                             :rowClassName="rowClassName"
                             :pagination="false">
                        <span slot="index" slot-scope="text, record, index">
                            {{ (pageVal.pageNo - 1) * pageVal.pageSize + index + 1 }}
                        </span>
                        <span slot="auditStatus" slot-scope="text"  :style="text !== '1'?'':'color:green'">
                            {{ text === '1' ? '已审计' : '未审计' }}
                        </span>
                        <span slot="itemParams" slot-scope="text" style="word-break: break-all">
                            <ellipsis :length="18" tooltip :fullString="text"></ellipsis>
                        </span>
                        <span slot="description" slot-scope="text">
                            <ellipsis :length="showTextNum" tooltip :fullString="text"></ellipsis>
                        </span>
                        <span slot="detail" slot-scope="text" class="table-operation">
                            <a @click="handleAuditLogs(text)" v-if="text.auditStatus !== '1'">审计</a>
                            <a @click="$refs.auditLogInfo.showModal(text)" v-if="text.auditStatus === '1'" style="color: #faad14;">查看</a>
                        </span>
                    </a-table>
                    <Page :totalCount="pageVal.total" :currentPage="pageVal.pageNo" ref="page"
                          :pageSize="pageVal.pageSize" @changePage="changePage"
                          @changePageSize="changePageSize" />
                </div>
            </div>
        </a-row>
        <iframe id="ifile" style="display: none"></iframe>
        <pl-lazy :time="500">
            <audit-log-info ref="auditLogInfo" />
        </pl-lazy>
        <div class="spinBox" v-if="spinning">{{spinText}}</div>
    </div>
</template>

<script>
import {mapState} from 'vuex'
import Page from 'module/pagination'
import ellipsis from 'module/ellipsis'
import moment from 'moment'
import verify from 'libs/verify'
import auditLogInfo from './auditLogInfo'

export default {
        name: 'audit_logs',
        components: {
            Page,
            ellipsis,
            auditLogInfo
        },
        data () {
            return {
                verify,
                searchErrorMsg:'',
                listT: [],
                page: {
                    pageNo: 1,
                    pageSize: 10
                },
                array: [ 10, 20, 30, 40 ],
                searchForm: {
                    userName: '',
                    loginIp: '',
                    date: [],
                    itemCode:undefined,
                    operateType: ''
                },
                startValue: null,
                endValue: null,
                columns: [
                    {title: '序号', key: 'index', width: '8%', align: 'center', scopedSlots: {customRender: 'index'}},
                    {title: '登录用户', dataIndex: 'userName', key: 'userName', width: '13%'},
                    /*{title: '用户角色', dataIndex: 'userRoleName', key: 'userRoleName',width: '100px',},*/
                    {title: '操作终端', dataIndex: 'loginIp', key: 'loginIp', width: '100px',},
                    {title: '操作时间', dataIndex: 'createTime', key: 'createTime', width: '14%'},
                    {title: '功能点', dataIndex: 'itemName', key: 'itemName', width: '10%'},
                    {
                        title: '详细信息',
                        dataIndex: 'itemParams',
                        key: 'itemParams', width: '15%',
                        scopedSlots: {customRender: 'itemParams'}
                    },
                    {
                        title: '操作结果', width: '15%',
                        key: 'description',
                        dataIndex: 'description',
                        scopedSlots: {customRender: 'description'}
                    },
                    {title: '审计状态', dataIndex: 'auditStatus', key: 'auditStatus', width: '90px',scopedSlots: {customRender: 'auditStatus'}},
                    {
                        title: '操作', width: '70px',
                        key: 'detail',
                        scopedSlots: {customRender: 'detail'}
                    }
                ],
                showTextNum:30,
                handleAuditLogFlag:false,
                userName:sessionStorage.getItem('user'),
                spinText:'请稍后...',
                spinning:false,
            }
        },
        methods: {
            handelLogs(text){
                let _this = this;
                _this.$axios.post (_this.$uurl + '/auditlog/signAuditLogInfo', text).then (response => {
                    let respData = response.data
                    if (respData.code === 0) {
                        // 处理审计
                        _this.handleAuditLogs(text, respData.data)
                    } else {
                        _this.$message.error (respData.message)
                    }
                }).catch (e => {
                    _this.$message.error ("其他错误")
                })
            },
            handleAuditLogs(text, signData) {
                this.spinning = true
                this.$post ('api/audit/handleAuditLogs',{logId:text.id,auditUserName:this.userName}).then (res => {
                    if (res.code === 0) {
                        this.init();
                    } else {
                        this.$message.error (res.message)
                    }
                    this.spinning = false
                })
            },
            emitEmpty (partant,name) {
                this[partant][name] = ''
                if(name=== 'loginIp'){
                    this.searchErrorMsg = ''
                }
                this.init();
            },
            reStore(){
                this.searchForm.userName = ''
                this.searchForm.loginIp = ''
                this.searchForm.itemCode = undefined
                this.searchForm.operateType = undefined
                this.startValue = null
                this.endValue = null
                this.page.pageNo = 1
                this.init();
            },
            validateSearchIP(text){
                text = text || ''
                text = text.replace(/\s/g, '')
                if (text.length > 30) {
                    text = text.substring(0, 30)
                }
                this.searchForm.loginIp = text
                this.searchErrorMsg = text ? (this.verify.ipAddress(text) ? '' : '请输入合法IP') : ''
            },
            /**
             * Function    : formalIP
             * Description : IP过滤器
             * Input       : none
             * Return      : none
             */
            formalIP(partant, name) {
                let a = this[partant][name]
                a = a.replace(/[^\d\.]/g, '')
                let arr = a.split('.')
                let b = ''
                arr.forEach((item, index) => {
                    if (item !== '') {
                        if (index === arr.length - 1) {
                            b = b + Number(item)
                        } else {
                            b = b + Number(item) + '.'
                        }
                    }
                })
                this[partant][name] = b
            },
            /*
             * 过滤输入框输入的特殊字符
             * */
            formatEnterContent(partant, name,type) {
                let b = this[partant][name];
                if(type==='1'){
                    b = b.replace(/[^/\u4e00-\u9fa5a-zA-Z0-9_]/ig, '');
                }else{
                    b = b.replace(/[^/a-zA-Z0-9]/ig, '');
                }
                if (b.length > 30) {
                    b = b.substring(0, 30)
                }
                this[partant][name] = b;
            },
            /**
             * Function    : disabledStartDate
             * Description : 对结束时间进行限制
             * Input       : startValue
             * Return      : None
             */
            disabledStartDate ( startValue ) {
                const endValue = this.endValue
                if (endValue) {
                    if (moment (startValue).format ('YYYY-MM-DD') === moment (endValue).format ('YYYY-MM-DD')) {
                        return false
                    }
                    return (
                      startValue.valueOf () <
                      moment ()
                        .startOf ('day')
                        .subtract (36, 'months') || startValue.valueOf () > endValue.valueOf ()
                    )
                }
                return (
                  startValue.valueOf () > moment () ||
                  startValue.valueOf () <
                  moment ()
                    .startOf ('day')
                    .subtract (36, 'months')
                )
            },
            /**
             * Function    : disabledEndDate
             * Description : 对结束时间进行限制
             * Input       : endValue
             * Return      : None
             */
            disabledEndDate ( endValue ) {
                const startValue = this.startValue
                if (startValue) {
                    return startValue.valueOf () >= endValue.valueOf () || endValue.valueOf () > moment ()
                }
                return (
                  endValue.valueOf () > moment () ||
                  endValue.valueOf () <
                  moment ()
                    .startOf ('day')
                    .subtract (36, 'months')
                )
            },
            /**
             * Function    : init
             * Description : 初始化加载页面
             * Input       : none
             * Return      : none
             */
            init () {
                this.$store.dispatch ('getAuditMedelsAct')
                this.loadPageData ()
            },

            /**
             * Function    : loadPageData
             * Description : 加载页面数据
             * Input       : None
             * Return      : None
             */
            loadPageData () {
                let _this = this
                let date = _this.searchForm.date
                let searchStartDate = ''
                let searchEndDate = ''
                if (this.endValue === null && this.startValue) {
                    searchStartDate = moment (this.startValue)
                      .format ('YYYY-MM-DD HH:mm:ss')
                      .valueOf ()
                }
                if (this.startValue === null && this.endValue) {
                    searchEndDate = moment (this.endValue)
                      .format ('YYYY-MM-DD HH:mm:ss')
                      .valueOf ()
                }
                if (this.startValue && this.endValue) {
                    searchStartDate = moment (this.startValue)
                      .format ('YYYY-MM-DD HH:mm:ss')
                      .valueOf ()
                    searchEndDate = moment (this.endValue)
                      .format ('YYYY-MM-DD HH:mm:ss')
                      .valueOf ()
                }
                let params = Object.assign ({}, _this.page,
                  {searchStartDate: searchStartDate},
                  {searchEndDate: searchEndDate},
                  {userName: _this.searchForm.userName},
                  {loginIp: _this.searchForm.loginIp},
                  {itemCode: _this.searchForm.itemCode},
                  {operateType: _this.searchForm.operateType}
                )
                _this.$store.dispatch ('findAuditLogsAct', params)
            },

            /**
             * Function    : loadPageData
             * Description : 重新加载加载页面数据
             * Input       : None
             * Return      : None
             */
            reloadPageData () {
                this.page.pageNo = 1
                this.loadPageData ()
            },

            /*查询*/
            handleSubmit (  ) {
                if(this.searchErrorMsg === ''){
                    this.page.pageNo = 1
                    this.reloadPageData ()
                }
            },
            changePage ( pageNo ) {
                this.page.pageNo = pageNo
                this.loadPageData ()
            },
            /*切换每页条数*/
            changePageSize ( vm ) {
                this.page.pageSize = vm
                this.page.pageNo = 1
                this.loadPageData ()
            },
            /**
             * Function    : handleCheckChange
             * Description : 选择树结构，值回显示在select里面
             * Input       : data 树节点数据
             * Return      : none
             */
            handleCheckChange ( data ) {
                this.listT = []
                this.listT.push ({
                    value: data[ 0 ].id,
                    title: data[ 0 ].title
                })
                this.searchForm.itemCode = data[ 0 ].id
                this.$refs.menSelect.visible = false
                data[ 0 ].selected = false
            },

            /**
             * Function    : rowClassName
             * Description : 篡改记录标红
             * Input       : data 树节点数据
             * Return      : none
             */
            rowClassName ( row ) {
                /*
                 if (row.itemCode === '40001011') {
                 return 'demo-table-info-row-warn';
                 }
                 */
                if (row.flag === '1') {
                    return 'demo-table-info-row-err'
                }
                return ''
            },
            /**
             * Function    : exportAuditLog
             * Description : 导出审计日志
             * Input       : none
             * Return      : none
             */
            exportAuditLogs() {
                let _this = this;
                _this.$confirm ({
                    title: `是否导出已完成审计的日志! `,
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        let url = '/audit/exportAuditLogs';
                        /*document.getElementById ('ifile').src = url + '?token=' + sessionStorage.token;
                        let timer = setInterval (function () {
                            let iframe = document.getElementById ('ifile')
                            let iframeDoc = iframe.contentDocument || iframe.contentWindow.document
                            if (iframeDoc) {
                                if (iframeDoc.readyState === 'complete' || iframeDoc.readyState === 'interactive') {
                                    clearInterval (timer)
                                }
                            }
                        }, 4000)*/

                        _this.spinning = true
                        _this.$get ('audit/exportAuditLogs').then (res => {
                            if (res.code === 0) {
                                _this.downLoadJson(res.data)
                            } else {
                                _this.$message.error (res.message)
                            }
                            _this.spinning = false
                        })
                    }
                })
            },

            downLoadJson(data){
                let blob = ''
                blob =new Blob([this.decodeToArrayBuffer (data.fileContent)],{type:"image/png"})
                let url =URL.createObjectURL(blob)
                let element = document.createElement('a')
                element.style.display = 'none'
                element.href= url
                element.download = data.fileName
                element.click()
            },
            decodeToArrayBuffer(str){
                let bstr = atob(str)
                let length = bstr.length
                let unit8Array = new Uint8Array(length)
                for(let i=0;i<length;i++){
                    unit8Array[i] = bstr.charCodeAt(i)
                }
                return unit8Array.buffer
            },

        },
        computed: {
            getItemsOpts () {
                return this.$store.state.sysAuditLog.auditItemsOpt
            },
            getLogsPageData () {
                return this.$store.state.sysAuditLog.auditLogsPageData
            },
            ...mapState ({
                pageVal: state => state.sysAuditLog.page
            })
        },
        created () {
            this.init ()
            /*this.handleAuditLogFlag =  this.hasPermission('audit:handleAuditLogs')
            if(!this.handleAuditLogFlag){
                this.columns = this.columns.splice(0,8)
            }*/
        },
        mounted(){

        },
        destroyed(){

        }
    }
</script>
<style type="text/css" scoped>
    .errorMsg {
        font-size: 12px;
        color: red;
        position: absolute;
        z-index: 1;
        top: 16px;
        width: 260px;
        text-align: left; line-height: 25px;
    }
</style>
<style type="text/css">
    .demo-table-info-row-warn td {
        color: #ff9900;
    }

    .demo-table-info-row-err td {
        color: red;
    }
</style>
